package com.insigma.business.qrcode.soldier.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.business.qrcode.soldier.dto.*;
import com.insigma.business.qrcode.soldier.entity.*;
import com.insigma.business.qrcode.soldier.service.ThirdPartyService;
import com.insigma.business.qrcode.soldier.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.logging.log4j.util.Strings;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.insigma.business.qrcode.soldier.request.ThirdPartyUriConstant.*;


@Slf4j
@Service("thirdPartyService")
public class ThirdPartyServiceImpl implements ThirdPartyService {

    private static Logger LOGGER = LoggerFactory.getLogger(ThirdPartyService.class);

    Cache<String, Map<String, SubsistenceEntity>> cache = CacheBuilder.newBuilder().expireAfterWrite(1L, TimeUnit.DAYS).build();

    Cache<String, TokenEntity> tokenCache = CacheBuilder.newBuilder().expireAfterWrite(15L, TimeUnit.SECONDS).build();


    @Autowired
    private RedisUtils redisUtils;

    public static final String REFRESHSECRETKEY_CACHE_KEY = "irs:refreshsecretKey:";

    /**
     * 获取请求秘钥
     *
     * @param appKey
     * @param secretKey
     * @return
     */
    private String getPersonRefreshSecret(String appKey, String secretKey) {


        Object object = redisUtils.get(REFRESHSECRETKEY_CACHE_KEY + appKey);
        if (ObjectUtil.isNotEmpty(object)) {
            return (String) object;
        }

        Long requestTime = System.currentTimeMillis();
        String sign = MD5Utils.encodeByMD5(appKey + secretKey + requestTime);

        String url = "https://interface.zjzwfw.gov.cn/gateway/app/refreshTokenByKey.htm?"
                + "requestTime=" + requestTime + "&appKey=" + appKey + "&sign=" + sign;

        TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        HttpClientBuilder clientBuilder = HttpClients.custom();
        CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appKey", appKey);
        jsonObject.put("sign", sign);
        jsonObject.put("requestTime", requestTime);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(jsonObject, requestHeaders);
        JSONObject json = restTemplate.postForObject(url, requestEntity, JSONObject.class);
        if ("00".equals(json.getString("code"))) {
            String requestSecret = json.getJSONObject("datas").getString("requestSecret");
            redisUtils.set(REFRESHSECRETKEY_CACHE_KEY, requestSecret, 14 * 60);
            return requestSecret;
        }

        log.error("IrsUtil-秘钥请求失败：{}", json);
        return null;
    }

    private Boolean checkCodeSuccess(JSONObject jsonObject) {
        if (jsonObject == null) {
            return false;
        }
        String code = jsonObject.getString("code");
        if ("0".equals(code)) {
            return true;
        }
        return false;
    }

    @Override
    public TokenEntity queryToken() {
        String response = OkHttp3Util.sendByPostJson(TOKEN_URI, "{}");
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String resultCode = jsonObject.getString("result_code");
            if (resultCode.equals("200")) {
                JSONArray data = jsonObject.getJSONArray("data");
                List<TokenEntity> tokenEntities = data.toJavaList(TokenEntity.class);
                if (!CollectionUtils.isEmpty(tokenEntities)) {
                    return tokenEntities.get(0);
                }
            }
        }
        return null;
    }

    @Override
    public ZSTokenEntity queryZSToken() {
        Map<String, String> bodyMap = Maps.newHashMap();
        bodyMap.put("grant_type", "client_credentials");

        Map<String, String> header = Maps.newHashMap();
        header.put("Authorization", "Basic MkRDN0NFNzM1RUVCNEUxMjg0MzNFNTE5NjE2MTNCREI6Njg3MDc5MzM5MTdCNDYyN0JBQUE0OEQyNDk4NUZCODc=");
        String response = OkHttp3Util.sendByPostMap(ZS_TOKEN_URI, bodyMap, header);

        if (response != null) {
            ZSTokenEntity zsTokenEntity = JSONObject.parseObject(response, ZSTokenEntity.class);
            return zsTokenEntity;
        }
        return null;
    }


    public TokenEntity queryUntilTokenSuccess() {
        int all = 20;
        for (int i = 0; i < all; i++) {
            TokenEntity tokenEntity = queryToken();
            if (tokenEntity != null) {
                return tokenEntity;
            }
        }
        return null;
    }

    public TokenEntity resetTokenEntity() {
        String key = "token";
        TokenEntity tokenEntity = queryUntilTokenSuccess();
        tokenCache.put(key, tokenEntity);
        return tokenEntity;
    }

    public TokenEntity getTokenEntity() {
        String key = "token";
        TokenEntity tokenInCache = tokenCache.getIfPresent(key);
        if (tokenInCache != null) {
            return tokenInCache;
        } else {
            return resetTokenEntity();
        }
    }

    @Override
    public InsuredEntity queryInsured(String idCardNo) {


        Map<String, String> map = Maps.newHashMap();
        map.put("sfzh", idCardNo);

        String result = OkHttp3Util.sendByPostMap(INSURED_URI, map);
        JSONObject jsonObject = JSON.parseObject(result);

        if (!checkCodeSuccess(jsonObject)) {
            return null;
        }

        JSONArray array = jsonObject.getJSONArray("result");
        for (int i = 0; i < array.size(); i++) {
            InsuredEntity object = array.getObject(i, InsuredEntity.class);
            return object;
        }

        return null;
    }

    @Override
    public List<InsuredInfoEntity> queryInusreList(String idCardNo, String name) {

        JSONObject json = new JSONObject();
        json.put("id_nbr", idCardNo);
        json.put("name", name);

        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);

            Map<String, String> headersMap = Maps.newHashMap();
            headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
            headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

            String sign = RSAUtils.sign(request, privateKey);

            Map<String, String> requestMap = Maps.newHashMap();
            requestMap.put("id_nbr", idCardNo);
            requestMap.put("name", name);
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData(INSURED_LIST_SHI_URI, requestMap, headersMap);
            if (response != null) {
                JSONObject jsonObject = JSON.parseObject(response);
                String resultCode = jsonObject.getString("result_code");
                if (resultCode.equals("200")) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null) {
                        return data.toJavaList(InsuredInfoEntity.class);
                    }
                }
            }
        } catch (Exception e) {
            log.error("error:{}", e);
        }
        return null;
    }

    @Override
    public void queryInusreListOfPerson(String companyName, String code) {

        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        JSONObject json = new JSONObject();
        json.put("ent_name", companyName);
        json.put("org_code", code);

        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);
            String sign = RSAUtils.sign(request, privateKey);

            Map<String, String> requestMap = Maps.newHashMap();
            json.put("ent_name", companyName);
            json.put("org_code", code);
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData("http://172.18.103.246:9009/ESBWeb/servlets/33.1111.zjhz.smzx.renshejucmpnyinsudinfo.SynReq@1.0", requestMap, headersMap);
            System.out.println(request);
        } catch (Exception e) {
            log.error("error:{}", e);
        }
    }

    public List<InsuredInfoEntity> queryInusreListOfShi(String idCardNo, String name) {
        JSONObject json = new JSONObject();
        json.put("id_nbr", idCardNo);
        json.put("name", name);

        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);
            String sign = RSAUtils.sign(request, privateKey);

            Map<String, String> requestMap = Maps.newHashMap();
            requestMap.put("id_nbr", idCardNo);
            requestMap.put("name", name);
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData(INSURED_LIST_SHI_URI, requestMap, headersMap);
            if (response != null) {
                JSONObject jsonObject = JSON.parseObject(response);
                String resultCode = jsonObject.getString("result_code");
                if (resultCode.equals("200")) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null) {
                        return data.toJavaList(InsuredInfoEntity.class);
                    }
                }
            }
        } catch (Exception e) {
            log.error("error:{}", e);
        }

        return null;
    }

    @Override
    public List<EducationEntity> queryEducationList(String idCardNo, String name) {


        Map<String, String> map = Maps.newHashMap();
        map.put("zjhm", idCardNo);
        map.put("xm", name);

        String result = OkHttp3Util.sendByPostMap(EDUCATION_URI, map);

        JSONObject jsonObject = JSON.parseObject(result);
        Object datas = jsonObject.get("datas");

        List<EducationEntity> list = Lists.newArrayList();
        if (datas instanceof JSONObject) {
            JSONObject object = (JSONObject) datas;
            EducationEntity educationEntity = object.toJavaObject(EducationEntity.class);
            if (educationEntity.getCheckrs().equals("1")) {
                list.add(educationEntity);
            }
        } else if (datas instanceof JSONArray) {
            JSONArray array = (JSONArray) datas;
            list = array.toJavaList(EducationEntity.class);
        }

        return list;
    }

    @Override
    public SubsistenceEntity querySubsistence(String idCardNo) {

        String key = "SUBSISTENCE";

        Map<String, SubsistenceEntity> ifPresent = cache.getIfPresent(key);
        if (ifPresent == null) {
            DateFormatUtils.format(new Date(), "YYYY-MM-DD");

            Date startDate = DateUtils.addMonths(new Date(), -1);
            String start = DateFormatUtils.format(startDate, "yyyy-MM-dd");
            String end = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
            List<SubsistenceEntity> subsistenceEntities = querySubsistenceByHttp(start, end);
            Map<String, SubsistenceEntity> collect = subsistenceEntities.stream().collect(Collectors.toMap(SubsistenceEntity::getAhap0015, s -> s));
            cache.put(key, collect);
            SubsistenceEntity subsistenceEntity = collect.get(idCardNo);
            return subsistenceEntity;
        } else {
            return ifPresent.get(idCardNo);
        }
    }

    //irs上有，但是有问题
    @Override
    public MedicalInsuranceConsumptionEntity queryMedicalInsuranceConsume(String idCardNo, String xm) {
        Date startDate = DateUtils.addYears(new Date(), -1);
        String start = DateFormatUtils.format(startDate, "yyyyMMdd");
        String end = DateFormatUtils.format(new Date(), "yyyyMMdd");

        String result = new RetireXmlUtil().ybXmlConvertString(xm, start,
                end, "330100", idCardNo);

        if (StringUtils.isBlank(result)) {
            return null;
        }

        try {
            Document document = DocumentHelper.parseText(result);
            Element element = document.getRootElement();

            Element content = element.element("CONTENT");
            Element head = element.element("HEAD");
            Element msg = head.element("ERRMSG");
            if (msg != null && "成功".equals(msg.getData())) {
                Iterator it = content.elementIterator();
                MedicalInsuranceConsumptionEntity hiInfo = new MedicalInsuranceConsumptionEntity();
                while (it.hasNext()) {
                    Element e = (Element) it.next();
                    String name = e.getQName().getName();
                    if ("SINO".equals(name)) {
                        hiInfo.setSino(e.getData().toString());
                    }
                    if ("PNAME".equals(name)) {
                        hiInfo.setPName(e.getData().toString());
                    }
                    if ("IDNO".equals(name)) {
                        hiInfo.setIdNo(e.getData().toString());
                    }
                    if ("PTMZZFA".equals(name)) {
                        hiInfo.setPtmzzfa(new BigDecimal(e.getData().toString()));
                    }
                    if ("PTMZZFB".equals(name)) {
                        hiInfo.setPtmzzfb(new BigDecimal(e.getData().toString()));
                    }
                    if ("PTMZZFC".equals(name)) {
                        hiInfo.setPtmzzfc(new BigDecimal(e.getData().toString()));
                    }
                    if ("PTMZZFD".equals(name)) {
                        hiInfo.setPtmzzfd(new BigDecimal(e.getData().toString()));
                    }
                    if ("PTMZZFE".equals(name)) {
                        hiInfo.setPtmzzfe(new BigDecimal(e.getData().toString()));
                    }
                    if ("PTMZZFF".equals(name)) {
                        hiInfo.setPtmzzff(new BigDecimal(e.getData().toString()));
                    }
                    if ("GDBZJEG".equals(name)) {
                        hiInfo.setGdbzjeg(new BigDecimal(e.getData().toString()));
                    }
                    if ("GDBZJEH".equals(name)) {
                        hiInfo.setGdbzjeh(new BigDecimal(e.getData().toString()));
                    }
                    if ("GDBZJEI".equals(name)) {
                        hiInfo.setGdbzjei(new BigDecimal(e.getData().toString()));
                    }
                    if ("YLZFK".equals(name)) {
                        hiInfo.setYlzfk(new BigDecimal(e.getData().toString()));
                    }
                    if ("PTMZZFL".equals(name)) {
                        hiInfo.setPtmzzfl(new BigDecimal(e.getData().toString()));
                    }
                    if ("GDBZJEM".equals(name)) {
                        hiInfo.setGdbzjem(new BigDecimal(e.getData().toString()));
                    }
                    if ("PTMZZFN".equals(name)) {
                        hiInfo.setPtmzzfn(new BigDecimal(e.getData().toString()));
                    }
                }
                return hiInfo;
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    //irs未找到的接口
    @Override
    public DisabledEntity queryDisabledInfo(String idCardNo) {
        JSONObject json = new JSONObject();
        json.put("idCard", idCardNo);

        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);
            String sign = RSAUtils.sign(request, privateKey);

            Map<String, String> requestMap = Maps.newHashMap();
            requestMap.put("idCard", idCardNo);
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData(DISABLED_URI, requestMap, headersMap);
            if (response != null) {
                JSONObject jsonObject = JSON.parseObject(response);
                String resultCode = jsonObject.getString("result_code");
                if (resultCode.equals("200")) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    List<DisabledEntity> disabledEntities = data.toJavaList(DisabledEntity.class);
                    if (!CollectionUtils.isEmpty(disabledEntities)) {
                        return disabledEntities.get(0);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //irs上没有,irs上有公积金接口但是调用报错
    @Override
    public List<ProvidentFundEntity> queryProvidentFund(String idCardNo, String name) {
        JSONObject json = new JSONObject();
        json.put("id_nbr", idCardNo);
        json.put("name", name);


        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);
            String sign = RSAUtils.sign(request, privateKey);

            Map<String, String> requestMap = Maps.newHashMap();
            requestMap.put("id_nbr", idCardNo);
            requestMap.put("name", name);
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData(PROVIDENT_FUND_URI, requestMap, headersMap);
            if (response != null) {
                JSONObject jsonObject = JSON.parseObject(response);
                String resultCode = jsonObject.getString("result_code");
                if (resultCode.equals("200")) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null) {
                        return data.toJavaList(ProvidentFundEntity.class);
                    }
                }
            }
        } catch (Exception e) {
            log.error("error:{}", e);
        }

        return null;
    }

    //irs上没有
    @Override
    public List<CarEntity> queryCarList(String idCardNo) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("sfzmhm", idCardNo);
//        String response = OkHttp3Util.sendFormData(CAR_URI, requestMap, null);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<CarEntity> carEntities = datas.toJavaList(CarEntity.class);
//                    return carEntities;
//                } else {
//                    return new ArrayList<>();
//                }
//            }
//        }

        return new ArrayList<>();
    }

    //irs上没有
    @Deprecated
    @Override
    public List<ShareholderEntity> queryShareholderList(String idCardNo) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("cardId", idCardNo);
//        String response = OkHttp3Util.sendFormData(SHAREHOLDER_URI, requestMap, null);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<ShareholderEntity> entityList = datas.toJavaList(ShareholderEntity.class);
//                    return entityList;
//                }
//            }
//        }
        return new ArrayList<>();
    }

    //    //irs上没有
    @Deprecated
    @Override
    public List<EnterpriseInfoEntity> queryEnterpriseList(String uniscid) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("uniscId", uniscid);
//
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//        String response = OkHttp3Util.sendFormData(ENTERPRISE_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<EnterpriseInfoEntity> entityList = datas.toJavaList(EnterpriseInfoEntity.class);
//                    return entityList;
//                }
//            }
//        }
        return new ArrayList<>();
    }

    //irs里面没有
    @Override
    public List<EnterpriseInfoEntity> queryEnterpriseListByName(String name) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("companyName", name);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//        String response = OkHttp3Util.sendFormData(ENTERPRISE_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<EnterpriseInfoEntity> entityList = datas.toJavaList(EnterpriseInfoEntity.class);
//                    return entityList;
//                }
//            }
//        }
        return Lists.newArrayList();
    }

    //irs里没有
    @Override
    public List<TaxEnterpriseInfoEntity> queryTaxEnterpriseList(String uniscid, String name) {
//        Map<String, String> requestMap = getTokenMap();
//        if (Strings.isNotBlank(uniscid)) {
//            requestMap.put("creditCode", uniscid);
//        }
//        if (Strings.isNotBlank(name)) {
//            requestMap.put("companyName", name);
//        }
//
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(TAX_ENTERPRISE_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<TaxEnterpriseInfoEntity> entityList = datas.toJavaList(TaxEnterpriseInfoEntity.class);
//                    return entityList;
//                }
//            }
//            checkIfMaxCount(code);
//        }
        return new ArrayList<>();
    }

    private void checkIfMaxCount(String code) {
        if (code.equals("18")) {
            throw new MaxCountException("");
        }
    }

    //irs没有
    @Override
    public List<HouseEntity> queryHouseList(String idCardNo, String name) {


//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("zjh", idCardNo);
//        requestMap.put("qlrmc", name);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//        String response = OkHttp3Util.sendFormData(HOUSE_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<HouseEntity> houseEntities = datas.toJavaList(HouseEntity.class);
//                    for (HouseEntity entity : houseEntities) {
//                        entity.convert();
//                    }
//                    return houseEntities;
//                } else {
//                    return new ArrayList<HouseEntity>();
//                }
//            }
//        }

        return new ArrayList<>();
    }

    //irs上没有
//    @Deprecated
//    @Override
//    public List<UntrustworthyEntity> queryUntrustworthy(String idCardNo, String name) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("cardId", idCardNo);
//        requestMap.put("name", name);
//        requestMap.put("executorNature", "自然人");
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(UNTRUST_WORTHY_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<UntrustworthyEntity> untrustworthyEntities = datas.toJavaList(UntrustworthyEntity.class);
//                    return untrustworthyEntities;
//                } else {
//                    return new ArrayList<UntrustworthyEntity>();
//                }
//            }
//        }
//        return null;
//    }

    //irs没有
//    @Deprecated
//    @Override
//    public List<CommunityCorrectionEntity> queryCommunityCorrectionList(String idCardNo) {
//
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("sfzh", idCardNo);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(COMMUNITY_CORRECTION_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<CommunityCorrectionEntity> communityCorrectionEntities = datas.toJavaList(CommunityCorrectionEntity.class);
//                    return communityCorrectionEntities;
//                }
//            }
//        }
//        return null;
//    }

    //irs
    @Override
    public ElectronicLicense queryElectronicLicense(String idCardNo) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("sfhm", idCardNo);
//        requestMap.put("User_Name", "退役局");
//        requestMap.put("Organization_Id", "tyj");
//        requestMap.put("Organization", "退役局");
//        requestMap.put("User_ID", "tyj");
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(ELECTRONIC_LICENSE_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                String datas = jsonObject.getString("datas");
//                if (Strings.isNotBlank(datas)) {
//                    JSONObject jsOi = JSONObject.parseObject(datas);
//                    String codeI = jsOi.getString("code");
//                    if ("01".equals(codeI)) {
//                        ElectronicLicense data = jsOi.getObject("data", ElectronicLicense.class);
//                        return data;
//                    }
//                }
//
//            }
//        }
        return null;
    }

    @Override
    public SoldierHouseholdRegistrationInfoDO queryHouseholdRegistrationInfo(String idCardNo, String name) {


        Map<String, String> map = Maps.newHashMap();
        map.put("gmsfhm", idCardNo);
        map.put("xm", name);
        String result = OkHttp3Util.sendByPostMap(GA_HOUSEHOLD_REGISTRATION_URI, map);
        log.info("info:{}", result);
        if (result != null) {
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("code");
            if ("00".equals(code)) {
                JSONObject data = jsonObject.getJSONObject("datas");
                if (data != null) {
                    SoldierHouseholdRegistrationInfoDO datarkxx = data.getObject("datarkxx", SoldierHouseholdRegistrationInfoDO.class);
                    return datarkxx;
                }
            }
            checkIfMaxCount(code);
        }

        return null;
    }

    //irs没有
    @Override
    public List<SoldierNewHouseholdRegistrationInfoDO> queryNewHouseholdRegistrationInfo(String idCardNo, String name) {

        JSONObject json = new JSONObject();
        json.put("id_nbr", idCardNo);
        json.put("name", name);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "k4am6ayo0rl2njf0upqg8ym0c");
        headersMap.put("appSecret", "axocwnnf0hiirpy3moim2fw58");

        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);
            String sign = RSAUtils.sign(request, privateKey);

            Map<String, String> requestMap = Maps.newHashMap();
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData(NEW_HOUSE_HOLD_UIR, requestMap, headersMap);
            log.info("公安户籍返回：{}", response);
            if (response != null) {
                JSONObject jsonObject = JSON.parseObject(response);
                String resultCode = jsonObject.getString("result_code");
                if (resultCode.equals("200")) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null) {
                        List<SoldierNewHouseholdRegistrationInfoDO> soldierNewHouseholdRegistrationInfoDOS = data.toJavaList(SoldierNewHouseholdRegistrationInfoDO.class);
                        Collections.sort(soldierNewHouseholdRegistrationInfoDOS, new Comparator<SoldierNewHouseholdRegistrationInfoDO>() {
                            @Override
                            public int compare(SoldierNewHouseholdRegistrationInfoDO o1, SoldierNewHouseholdRegistrationInfoDO o2) {
                                return o2.getAddr_date().compareTo(o1.getAddr_date());
                            }
                        });
                        return soldierNewHouseholdRegistrationInfoDOS;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<DestituteInfoEntity> queryDestituteInfo(String idCardNo, String name) {
        Map<String, String> requestMap = getTokenMap();
        requestMap.put("cardId", idCardNo);
        requestMap.put("name", name);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        String response = OkHttp3Util.sendFormData(DESTITUTE_URI, requestMap, headersMap);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<DestituteInfoEntity> destituteInfoEntities = datas.toJavaList(DestituteInfoEntity.class);
                    return destituteInfoEntities;
                } else {
                    return new ArrayList<>();
                }
            }
            checkIfMaxCount(code);
        }
        return null;
    }

//    @Deprecated
//    @Override
//    public List<SocialSecurityEntity> querySocialSecurity(String idCardNo, String name) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("AAC002", idCardNo);
//        requestMap.put("aac003", name);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(SOCIAL_SECURITY_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<SocialSecurityEntity> result = datas.toJavaList(SocialSecurityEntity.class);
//                    return result;
//                } else {
//                    return new ArrayList<>();
//                }
//            }
//        }
//        return null;
//    }

    @Override
    public List<EffectiveJudgmentEntity> queryEffectiveJudgmentList(String idCardNo, String name) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("cardId", idCardNo);
//        requestMap.put("name", name);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(EFFECTIVE_JUDGMENT_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<EffectiveJudgmentEntity> result = datas.toJavaList(EffectiveJudgmentEntity.class);
//                    return result;
//                } else {
//                    return new ArrayList<>();
//                }
//            }
//        }
        return null;
    }

    @Override
    public List<GovernmentPensionInsuranceEntity> queryGovernmentPensionInsuranceList(String idCardNo, String name) {
        Map<String, String> requestMap = getTokenMap();
        requestMap.put("cardId", idCardNo);
        requestMap.put("name", name);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        String response = OkHttp3Util.sendFormData(GOVERNMENT_PENSION_INSURANCEENTITY_URI, requestMap, headersMap);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<GovernmentPensionInsuranceEntity> result = datas.toJavaList(GovernmentPensionInsuranceEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
        }
        return null;
    }

    @Deprecated
    @Override
    public List<FloatingPopulationEntity> queryFloatingPopulationList(String idCardNo, String name) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("cardId", idCardNo);
//        requestMap.put("name", name);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(FLOATING_POPULATION_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<FloatingPopulationEntity> result = datas.toJavaList(FloatingPopulationEntity.class);
//                    return result;
//                } else {
//                    return new ArrayList<>();
//                }
//            }
//        }
        return new ArrayList<>();
    }

    @Override
    public List<MaritalInfoEntity> queryMaritalInfo(String idCardNo, String name, String sex, String birthday) {


        Map<String, String> map = Maps.newHashMap();
        map.put("cardId", idCardNo);
        map.put("name", name);
        map.put("sex", sex);
        map.put("birthday", birthday);
        String result = OkHttp3Util.sendByPostMap(MARITAL_INFO_URI, map);
        log.info("info:{}", result);
        if (result != null) {
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("code");
            if ("00".equals(code)) {
                JSONArray data = jsonObject.getJSONArray("datas");
                if (data != null) {
                    return data.toJavaList(MaritalInfoEntity.class);
                }
            }
        }

        return null;
    }

    @Override
    public List<HuKouEntity> queryHuKouInfo(String idCardNo) {
        ZSTokenEntity zsTokenEntity = queryZSToken();
        Map<String, String> map = Maps.newHashMap();
        map.put("id_nbr", idCardNo);

        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put("Authorization", zsTokenEntity.getAccessToken());
        String result = OkHttp3Util.sendByPostMap(ZS_HU_KOU_URI, map, headerMap);
        if (result != null) {
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("result_code");
            if ("200".equals(code)) {
                JSONArray data = jsonObject.getJSONArray("data");
                if (data != null) {
                    return data.toJavaList(HuKouEntity.class);
                }
            }
        }
        return null;
    }

    @Override
    public List<HuKouEntity> queryHuKouBen(String idCardNo) {
        ZSTokenEntity zsTokenEntity = queryZSToken();
        Map<String, String> map = Maps.newHashMap();
        map.put("id_nbr", idCardNo);

        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put("Authorization", zsTokenEntity.getAccessToken());
        String result = OkHttp3Util.sendByPostJson(HU_KOU_BEN_URI, JSON.toJSONString(map), headerMap);
        if (result != null) {
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("result_code");
            if ("200".equals(code)) {
                JSONArray data = jsonObject.getJSONArray("data");
                if (data != null) {
                    return data.toJavaList(HuKouEntity.class);
                }
            }
        }
        return null;
    }

    @Override
    public HealthCodeEntity queryHealthInfo(String idCardNo) {
        ZSTokenEntity zsTokenEntity = queryZSToken();
        Map<String, String> map = Maps.newHashMap();
        map.put("idCard", idCardNo);
        map.put("phone", "17800000000");

        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put("Authorization", zsTokenEntity.getAccessToken());
        String result = OkHttp3Util.sendByPostJson("http://172.18.103.246:10005/api/v1/source/10000015191", JSON.toJSONString(map), headerMap);
        if (result != null) {
            JSONObject jsonObject = JSON.parseObject(result);
            String code = jsonObject.getString("result_code");
            return jsonObject.getObject("data", HealthCodeEntity.class);
        }
        return null;
    }

    @Override
    public List<HospitalizedInfoEntity> hospitalizedInfo(String PNAME, String year, String IDNO) {

        String soapAction = "http://service.neusoft.com";
        String url3 = "http://172.18.74.240:8001/hzws/services/NwsServer";
        String msgcode = "YB0150";
        String sndMsgId = "1589768236295";
        String SNDTIME = String.valueOf(System.currentTimeMillis());

        String SNDCODE = "TYDWJK";

        String interactXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<ROOT>" +
                "<HEAD>" +
                "<MSGCODE>" + msgcode + "</MSGCODE>" +

                "<SNDCODE>" + SNDCODE + "</SNDCODE>" +
                "<SNDMSGID>" + sndMsgId + "</SNDMSGID>" +
                "<USERNAME>fubin</USERNAME>" +
                "<SNDTIME>" + SNDTIME + "</SNDTIME>" +
                "</HEAD>" +
                "<CONTENT>" +
                "<YEAR>" + year + "</YEAR>" +
                "<IDNO>" + IDNO + "</IDNO>" +
                "<PNAME>" + PNAME + "</PNAME>" +
                "</CONTENT>" +
                "</ROOT>";
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        String res = null;
        try {

            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(url3);
            call.setOperationName(new QName(soapAction, "receive"));

            call.addParameter(new QName(soapAction, "msgCode"),
                    org.apache.axis.encoding.XMLType.XSD_STRING,
                    javax.xml.rpc.ParameterMode.IN);
            call.addParameter(new QName(soapAction, "sndMsgId"),
                    org.apache.axis.encoding.XMLType.XSD_STRING,
                    javax.xml.rpc.ParameterMode.IN);
            call.addParameter(new QName(soapAction, "interactXml"),
                    org.apache.axis.encoding.XMLType.XSD_STRING,
                    javax.xml.rpc.ParameterMode.IN);
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);


            call.setUseSOAPAction(true);
            call.setSOAPActionURI(soapAction + "/receive");

            res = String.valueOf(call.invoke(new Object[]{msgcode, sndMsgId, interactXml}));

        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Strings.isBlank(res)) {
            return null;
        }

        List<HospitalizedInfoEntity> row = QueryResult.readXMLToList("ROW", res, HospitalizedInfoEntity.class);
        return row;
    }

    @Override
    public List<HospitalizedInfoEntity> hospitalizedInfo(String realName, String idCardNo) {
        return hospitalizedInfo(realName, String.valueOf(DateUtil.year(new Date())), idCardNo);
    }

    @Override
    public String getYhMessageToken() {
        Map<String, String> requestMap = Maps.newHashMap();
        requestMap.put("client_id", "risen_kpcPGZ4lY43vlG4O5fmbkQ");
        requestMap.put("grant_type", "client_credentials");
        requestMap.put("scope", "resource");
        requestMap.put("client_secret", "7NKTDm3vj3i5WwBPBmrC3dJFMhZKL7CFlaxKh3GVDZViWu6E2VGd293mDGDFGCpw");
        String s = OkHttp3Util.sendWwwFormData("http://10.71.166.51/smsservice/public/oauth2/token.do", requestMap);

        JSONObject object = JSONObject.parseObject(s);
        return object.getString("access_token");
    }


    @Override
    public String sendYhMessage(String mobile, String message, String token) {
        return null;
    }

    @Override
    public List<WestLakeRecordEntity> queryWestLakeRecord(String startTime, String endTime) {
        log.info("获取西湖景区记录：{}，{}", startTime, endTime);

        String template = "https://www.westlakedata.com/ticket/parkQrcodeInfo/getQrCodeByEnterTheParkByTime?startTime=%s&endTime=%s";
        String s = OkHttp3Util.sendByGetUrl(String.format(template, startTime, endTime));
        if (Strings.isNotBlank(s)) {
            JSONObject object = JSONObject.parseObject(s);
            JSONObject data = object.getJSONObject("data");
            if (data != null) {
                JSONArray list = data.getJSONArray("list");
                if (list != null) {
                    return list.toJavaList(WestLakeRecordEntity.class);
                }
            }
        }
        return null;
    }

    @Override
    public List<UnemploymentRegistrationEntity> queryUnemploymentRegistration(String idCardNo, String name) {
        JSONObject json = new JSONObject();
        json.put("id_nbr", idCardNo);
        json.put("name", name);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);
            String sign = RSAUtils.sign(request, privateKey);

            Map<String, String> requestMap = Maps.newHashMap();
            requestMap.put("id_nbr", idCardNo);
            requestMap.put("name", name);
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData(UNEMPLOYMENT_REGISTRATION_URI, requestMap, headersMap);
            if (response != null) {
                JSONObject jsonObject = JSON.parseObject(response);
                String resultCode = jsonObject.getString("result_code");
                if (resultCode.equals("200")) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null) {
                        return data.toJavaList(UnemploymentRegistrationEntity.class);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<SubsistenceAllowanceEntity> querySubsistenceAllowance(String idCardNo, String name) {
        log.info("查询低保信息,{}", idCardNo);
        Map<String, String> requestMap = getTokenMap();
        requestMap.put("mhzsfz", idCardNo);
        requestMap.put("mhz", name);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        String response = OkHttp3Util.sendFormData(SUBSISTENCE_ALLOWANCE_URI, requestMap, headersMap);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<SubsistenceAllowanceEntity> result = datas.toJavaList(SubsistenceAllowanceEntity.class);

                    if (!CollectionUtils.isEmpty(result)) {
                        for (SubsistenceAllowanceEntity subsistenceAllowanceEntity : result) {
                            subsistenceAllowanceEntity.convert();
                        }
                    }
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
            checkIfMaxCount(code);
            return null;
        }
        return new ArrayList<>();
    }

    @Override
    public List<LowSideEntity> queryLowSide(String idCardNo, String name) {
        log.info("查询低边信息,{}", idCardNo);
        Map<String, String> requestMap = getTokenMap();
        requestMap.put("mhzsfz", idCardNo);
        requestMap.put("mhz", name);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        String response = OkHttp3Util.sendFormData(LOW_SIDE_URI, requestMap, headersMap);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<LowSideEntity> result = datas.toJavaList(LowSideEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
            checkIfMaxCount(code);
            return null;
        }
        return new ArrayList<>();
    }

    @Override
    public List<ExtremelyPoorEntity> queryExtremelyPoor(String idCardNo, String name) {
        log.info("查询特困信息,{}", idCardNo);
        Map<String, String> requestMap = getTokenMap();
        requestMap.put("cardId", idCardNo);
        requestMap.put("name", name);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        String response = OkHttp3Util.sendFormData(EXTREMELY_POOR_URI, requestMap, headersMap);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<ExtremelyPoorEntity> result = datas.toJavaList(ExtremelyPoorEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
            checkIfMaxCount(code);
            return null;
        }
        return new ArrayList<>();
    }

    @Override
    public List<EnterpriseCreditRatingEntity> queryEnterpriseCreditRating(String name) {

        return Collections.emptyList();
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("NSRMC", name);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(ENTERPRISE_CREDIT_RATING_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<EnterpriseCreditRatingEntity> destituteInfoEntities = datas.toJavaList(EnterpriseCreditRatingEntity.class);
//                    return destituteInfoEntities;
//                } else {
//                    return new ArrayList<>();
//                }
//            }
//            checkIfMaxCount(code);
//        }
//        return null;
    }

//    @Deprecated
//    @Override
//    public List<DeadInfoEntity> queryDeadInfo(String idCardNo) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("VC_SFZHM", idCardNo);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(DEAD_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<DeadInfoEntity> result = datas.toJavaList(DeadInfoEntity.class);
//                    return result;
//                } else {
//                    return new ArrayList<>();
//                }
//            }
//            checkIfMaxCount(code);
//        }
//        return null;
//    }


    @Override
    @Deprecated
    public List<DeadInfoEntity> queryDeadInfoOfDate(String date) {
        Map<String, String> requestMap = getTokenMap();
        requestMap.put("SWRQ", date);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        String response = OkHttp3Util.sendFormData(DEAD_DATE_URI, requestMap, headersMap);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<DeadInfoEntity> result = datas.toJavaList(DeadInfoEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
            checkIfMaxCount(code);
        }
        return null;
    }

    @Override
    public List<EnterprisePetitionEntity> queryEnterprisePetition(String orgName) {
        Map<String, String> requestMap = getTokenMap();
        requestMap.put("uniscIdOrName", orgName);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");

        String response = OkHttp3Util.sendFormData(ENTERPRISE_PETITION_URI, requestMap, headersMap);
        if (response != null) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (code.equals("00")) {
                JSONArray datas = jsonObject.getJSONArray("datas");
                if (datas != null) {
                    List<EnterprisePetitionEntity> result = datas.toJavaList(EnterprisePetitionEntity.class);
                    return result;
                } else {
                    return new ArrayList<>();
                }
            }
            checkIfMaxCount(code);
        }
        return null;
    }

    public Map<String, String> getTokenMap() {
        TokenEntity tokenEntity = getTokenEntity();
        long l = System.currentTimeMillis();
        String str = tokenEntity.getAppKey() + tokenEntity.getRequestSecret() + l;
        String sign = MD5Utils.encodeByMD5(str);

        Map<String, String> map = Maps.newHashMap();
        map.put("requestTime", String.valueOf(l));
        map.put("appKey", tokenEntity.getAppKey());
        map.put("sign", sign);
        return map;
    }

    private List<SubsistenceEntity> querySubsistenceByHttp(String start, String end) {


        JSONObject o = new JSONObject();
        o.put("jzksrq", start);
        o.put("jzjsrq", end);

        String s = OkHttp3Util.sendByPostJson(SUBSISTENCE_URI, o.toJSONString());
        JSONObject jsonObject = JSON.parseObject(s);

        JSONArray array = jsonObject.getJSONArray("data");
        if (array == null) {
            return new ArrayList<>();
        }

        List<SubsistenceEntity> list = array.toJavaList(SubsistenceEntity.class);
        return list;
    }

//    public List<SocialSecurityEntity> aa(String idCardNo, String name) {
//        Map<String, String> requestMap = getTokenMap();
//        requestMap.put("AAC002", idCardNo);
//        requestMap.put("aac003", name);
//        Map<String, String> headersMap = Maps.newHashMap();
//        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
//        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
//
//        String response = OkHttp3Util.sendFormData(SOCIAL_SECURITY_URI, requestMap, headersMap);
//        if (response != null) {
//            JSONObject jsonObject = JSON.parseObject(response);
//            String code = jsonObject.getString("code");
//            if (code.equals("00")) {
//                JSONArray datas = jsonObject.getJSONArray("datas");
//                if (datas != null) {
//                    List<SocialSecurityEntity> result = datas.toJavaList(SocialSecurityEntity.class);
//                    return result;
//                } else {
//                    return new ArrayList<>();
//                }
//            }
//        }
//        return null;
//    }


    @Override
    public List<FlexibleEmploymentEntity> queryFlexibleEmployment(String realName, String idCardNo) {
        JSONObject json = new JSONObject();
        json.put("name", realName);
        json.put("id_nbr", idCardNo);
        Map<String, String> headersMap = Maps.newHashMap();
        headersMap.put("appKey", "9jr4cre2i8eoj8iyv68ricmyo");
        headersMap.put("appSecret", "bsfepp9ieedn3g5trmc74owfu");
        try {
            String request = RSAUtils.encryptByPrivateKey(json.toJSONString(), privateKey);
            String sign = RSAUtils.sign(request, privateKey);
            Map<String, String> requestMap = Maps.newHashMap();
            requestMap.put("request", request);
            requestMap.put("sign", sign);
            String response = OkHttp3Util.sendFormData("http://172.18.103.246:9009/ESBWeb/servlets/33.1111.zjhz.smzx.renshejuemppromtenj.SynReq@1.0", requestMap, headersMap);
            if (response != null) {
                JSONObject jsonObject = JSON.parseObject(response);
                String code = jsonObject.getString("result_code");
                if (code.equals("200")) {
                    JSONArray datas = jsonObject.getJSONArray("data");
                    if (datas != null) {
                        List<FlexibleEmploymentEntity> result = datas.toJavaList(FlexibleEmploymentEntity.class);
                        return result;
                    } else {
                        return new ArrayList<>();
                    }
                }
            }

        } catch (Exception e) {
            log.error("{}", e);
        }
        return null;
    }


    @Override
    public Boolean isStudent(String idCardNo) throws DocumentException {
        String result = getStudentFromYbj(idCardNo);
        Document document = DocumentHelper.parseText(result);
        Element element = document.getRootElement();
        Element content = element.element("CONTENT");
        Element head = element.element("HEAD");
        Element msg = head.element("ERRMSG");
        if (msg != null && "成功".equals(msg.getData())) {
            Element cbbz = content.element("CBBZ");
            System.out.println(cbbz.getTextTrim());
            if ("是".equals(cbbz.getTextTrim())) {
                return true;
            }
        }
        return false;
    }


    @Override
    public ResidentInfo queryZyqtResidentByIdCardNoAndName(String name, String idCardNo) {
        List<ResidentInfo> residentInfos = queryZyqtResidentList(name, 1, 1000);
        if (!CollectionUtils.isEmpty(residentInfos)) {
            for (ResidentInfo residentInfo : residentInfos) {
                String endChar = idCardNo.substring(idCardNo.length() - 2, idCardNo.length());
                if (residentInfo.getIdno() == null || !residentInfo.getIdno().endsWith(endChar)) {
                    continue;
                }

                ResidentInfo residentInfo1 = queryZyqtResidentInfo(residentInfo.getPatientId());

                if (residentInfo1 != null && idCardNo.equals(residentInfo1.getIdno())) {
                    return residentInfo1;
                }
            }
        }
        return null;
    }

    private JSONObject buildBaseZyqtRequest(String interfaceCode, Map<String, Object> map) {
        JSONObject object = new JSONObject();
        object.put("interfaceCode", interfaceCode);
        object.put("paramMap", map);
        return object;
    }

    private JSONObject buildBaseZyqtRequest(String interfaceCode, String patientId) {
        JSONObject object = new JSONObject();
        object.put("interfaceCode", interfaceCode);
        Map<String, String> map = new HashMap<>();
        map.put("patientId", patientId);
        object.put("paramMap", map);
        return object;
    }


    @Override
    public List<ResidentInfo> queryZyqtResidentList(String name, Integer pageNo, Integer pageSize) {

        Map<String, Object> request = new HashMap<>();
        request.put("name", name);
        request.put("pageIndex", pageNo);
        request.put("pageSize", pageSize);
        JSONObject object = buildBaseZyqtRequest("QT001", request);
        String s = OkHttp3Util.sendByPostJson(ZYQT_URI, object.toJSONString());
        JSONObject resObj = JSONObject.parseObject(s);
        if (resObj.getInteger("code").equals(0)) {
            JSONObject data = resObj.getJSONObject("data");
            JSONArray list = data.getJSONArray("list");
            List<ResidentInfo> residentInfos = list.toJavaList(ResidentInfo.class);
            return residentInfos;
        }

        return null;
    }

    @Override
    public ResidentInfo queryZyqtResidentInfo(String patientId) {
        JSONObject object = buildBaseZyqtRequest("QT002", patientId);
        String s = OkHttp3Util.sendByPostJson(ZYQT_URI, object.toJSONString());
        JSONObject resObj = JSONObject.parseObject(s);
        if (resObj.getInteger("code").equals(0)) {
            return resObj.getObject("data", ResidentInfo.class);
        }
        return null;
    }

    @Override
    public List<ConsultationInfo> queryZyqtConsultationList(String patientId) {
        Map<String, Object> request = new HashMap<>();
        request.put("patientId", patientId);
        request.put("pageIndex", 1);
        request.put("pageSize", 10000);
        JSONObject object = buildBaseZyqtRequest("QT003", request);
        String s = OkHttp3Util.sendByPostJson(ZYQT_URI, object.toJSONString());
        JSONObject resObj = JSONObject.parseObject(s);
        if (resObj.getInteger("code").equals(0)) {
            JSONObject data = resObj.getJSONObject("data");
            JSONArray list = data.getJSONArray("list");
            List<ConsultationInfo> residentInfos = list.toJavaList(ConsultationInfo.class);
            return residentInfos;
        }

        return null;
    }

    @Override
    public List<ConsultationInfo> queryZyqtConsultationListWithPrescribeInfo(String patientId) {
        if (Strings.isBlank(patientId)) {
            return null;
        }
        List<ConsultationInfo> consultationInfos = queryZyqtConsultationList(patientId);
        if (!CollectionUtils.isEmpty(consultationInfos)) {
            for (ConsultationInfo consultationInfo : consultationInfos) {
                List<PrescribeInfo> prescribeInfos = queryZyqtPrescribeInfoList(consultationInfo.getJiuzhenId());
                if (!CollectionUtils.isEmpty(prescribeInfos)) {
                    consultationInfo.setPrescribeInfos(prescribeInfos);
                }
            }
        }
        return consultationInfos;
    }

    @Override
    public List<PhysicalExaminationInfo> queryZyqtPhysicalExaminationInfoList(String name, String dateOfBirth) {
        Map<String, Object> request = new HashMap<>();
        request.put("name", name);
        request.put("dateOfBirth", dateOfBirth);
        request.put("pageIndex", 1);
        request.put("pageSize", 10000);
        JSONObject object = buildBaseZyqtRequest("QT005", request);
        String s = OkHttp3Util.sendByPostJson(ZYQT_URI, object.toJSONString());
        JSONObject resObj = JSONObject.parseObject(s);
        if (resObj.getInteger("code").equals(0)) {
            JSONObject data = resObj.getJSONObject("data");
            JSONArray list = data.getJSONArray("list");
            List<PhysicalExaminationInfo> residentInfos = list.toJavaList(PhysicalExaminationInfo.class);
            return residentInfos;
        }
        return null;
    }

    @Override
    public List<PrescribeInfo> queryZyqtPrescribeInfoList(String jiuzhenId) {
        Map<String, Object> request = new HashMap<>();
        request.put("jiuzhenId", jiuzhenId);
        request.put("pageIndex", 1);
        request.put("pageSize", 10000);
        JSONObject object = buildBaseZyqtRequest("QT004", request);
        String s = OkHttp3Util.sendByPostJson(ZYQT_URI, object.toJSONString());
        JSONObject resObj = JSONObject.parseObject(s);
        if (resObj.getInteger("code").equals(0)) {
            JSONObject data = resObj.getJSONObject("data");
            JSONArray list = data.getJSONArray("list");
            List<PrescribeInfo> residentInfos = list.toJavaList(PrescribeInfo.class);
            return residentInfos;
        }
        return null;
    }


    private String getStudentFromYbj(String IDNO) {
        String soapAction = "http://service.neusoft.com";

        String url3 = "http://172.18.74.240:8001/hzws/services/NwsServer?wsdl";

        String msgcode = "YB0192";
        String sndMsgId = "158976823638";
        String MSGTOKEN = "TYDWJK";
        String SNDCODE = "TYDWJK";

        String interactXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<ROOT>" +
                "<HEAD>" +
                "<MSGCODE>" + msgcode + "</MSGCODE>" +
                "<MSGTOKEN>" + MSGTOKEN + "</MSGTOKEN>" +
                "<SNDCODE>" + SNDCODE + "</SNDCODE>" +
                "<SNDMSGID>" + sndMsgId + "</SNDMSGID>" +
                "<USERNAME>退役军人</USERNAME>" +
                "<SNDTIME>" + sndMsgId + "</SNDTIME>" +
                "</HEAD>" +
                "<CONTENT>" +
                "<IDNO>" + IDNO + "</IDNO>" +
                "</CONTENT>" +
                "</ROOT>";
        System.out.println(interactXml);
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        String res = null;
        try {

            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(url3);
            call.setOperationName(new QName(soapAction, "receive"));

            call.addParameter(new QName(soapAction, "msgCode"),
                    org.apache.axis.encoding.XMLType.XSD_STRING,
                    javax.xml.rpc.ParameterMode.IN);
            call.addParameter(new QName(soapAction, "sndMsgId"),
                    org.apache.axis.encoding.XMLType.XSD_STRING,
                    javax.xml.rpc.ParameterMode.IN);
            call.addParameter(new QName(soapAction, "interactXml"),
                    org.apache.axis.encoding.XMLType.XSD_STRING,
                    javax.xml.rpc.ParameterMode.IN);
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);


            call.setUseSOAPAction(true);
            call.setSOAPActionURI(soapAction + "/receive");

            res = String.valueOf(call.invoke(new Object[]{msgcode, sndMsgId, interactXml}));

        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        System.out.println(res);
        return res;
    }


}
